﻿#region BSD License
/* 
Copyright (c) 2010, NETFx
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Clarius Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
// Originally appeared in http://haacked.com/archive/2009/01/14/named-formats-redux.aspx
// Authored by Henri Wiechers
// Ported to NETFx by Daniel Cazzulino
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SmartStringResources
{
	public static class StringFormatWithExtension
	{
		private static T ParseFormatString<T>(this string format, Action<char> charDelegate, Action<string> expressionDelegate, Func<T> resultDelegate)
		{
			if (format == null)
				throw new ArgumentNullException("format");

			if (charDelegate == null)
				charDelegate = c => { };

			if (expressionDelegate == null)
				expressionDelegate = expression => { };

			if (resultDelegate == null)
				throw new ArgumentNullException("resultDelegate");

			using (var reader = new StringReader(format))
			{
				var expression = new StringBuilder();
				var @char = -1;

				var state = State.OutsideExpression;
				do
				{
					switch (state)
					{
						case State.OutsideExpression:
							@char = reader.Read();
							switch (@char)
							{
								case -1:
									state = State.End;
									break;
								case '{':
									state = State.OnOpenBracket;
									break;
								case '}':
									state = State.OnCloseBracket;
									break;
								default:
									charDelegate((char)@char);
									break;
							}
							break;
						case State.OnOpenBracket:
							@char = reader.Read();
							switch (@char)
							{
								case -1:
									throw new FormatException();
								case '{':
									charDelegate('{');
									state = State.OutsideExpression;
									break;
								default:
									expression.Append((char)@char);
									state = State.InsideExpression;
									break;
							}
							break;
						case State.InsideExpression:
							@char = reader.Read();
							switch (@char)
							{
								case -1:
									throw new FormatException();
								case '}':
									expressionDelegate(expression.ToString());
									expression.Length = 0;
									state = State.OutsideExpression;
									break;
								default:
									expression.Append((char)@char);
									break;
							}
							break;
						case State.OnCloseBracket:
							@char = reader.Read();
							switch (@char)
							{
								case '}':
									charDelegate('}');
									state = State.OutsideExpression;
									break;
								default:
									throw new FormatException();
							}
							break;
						default:
							throw new InvalidOperationException("Invalid state.");
					}
				} while (state != State.End);
			}

			return resultDelegate();
		}

		/// <summary>
		/// Formats the string with the given array of tuple objects. 
		/// Expression like {Id} are replaced with the corresponding 
		/// tuple value in the <paramref name="parameters"/>.
		/// </summary>
		/// <param name="format" this="true">The string to format</param>
		/// <param name="parameters">The parameters name and values</param>
		public static string FormatWith(this string format, params Tuple<string, object>[] parameters)
		{
			var result = new StringBuilder(format.Length * 2);
			return ParseFormatString(format, c => result.Append(c), expression => result.Append(OutExpression(parameters, expression)), () => result.ToString());
		}

		/// <summary>
		/// Gets the unique parameters of the specified format string.
		/// Parameters are expressed like {Id} and can be escaped
		/// with double braces, like {{escaped}}
		/// </summary>
		/// <param name="format" this="true">The string to format</param>
		public static IEnumerable<FormatExpression> GetParameters(this string format)
		{
			if (format == null)
				return Enumerable.Empty<FormatExpression>();

			var list = new List<string>();
			return ParseFormatString(format, c => { }, list.Add, () => list.Select(GetFormatExpression).Distinct(new FormatExpressionComparer()));
		}

		private static FormatExpression GetFormatExpression(string expression)
		{
			var format = "";
			var colonIndex = expression.IndexOf(':');

			if (colonIndex > 0)
			{
				format = expression.Substring(colonIndex + 1);
				expression = expression.Substring(0, colonIndex);
			}

			return new FormatExpression { Name = expression, Format = format };
		}

		private static string OutExpression(IEnumerable<Tuple<string, object>> parameters, string expression)
		{
			var formatExpression = GetFormatExpression(expression);

			var parameter = parameters.FirstOrDefault(p => p.Item1 == formatExpression.Name);
			if (parameter != null)
			{
				if (string.IsNullOrEmpty(formatExpression.Format))
					return Convert.ToString(parameter.Item2);

				return string.Format(string.Format("{{0:{0}}}", formatExpression.Format), parameter.Item2);
			}

			return string.Empty;
		}

		private enum State
		{
			OutsideExpression,
			OnOpenBracket,
			InsideExpression,
			OnCloseBracket,
			End
		}
	}
}